<template>
  <view class="service-add-container">
    <view class="page-header">
      <text class="page-title">新增服务</text>
      <text class="page-subtitle">添加新的医疗服务项目</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">服务名称</text>
          <uni-easyinput 
            v-model="formData.service_name"
            placeholder="请输入服务名称"
            :maxlength="100"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.service_name" class="error-text">{{ errors.service_name }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">服务代码</text>
          <uni-easyinput 
            v-model="formData.service_code"
            placeholder="请输入服务代码（选填）"
            :maxlength="50"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">服务类型</text>
          <radio-group @change="onServiceTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.service_type === 1" color="#007aff"/>
              <text class="radio-text">治疗</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.service_type === 2" color="#007aff"/>
              <text class="radio-text">保养</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.service_type === 3" color="#007aff"/>
              <text class="radio-text">其他</text>
            </label>
          </radio-group>
          <text v-if="errors.service_type" class="error-text">{{ errors.service_type }}</text>
        </view>
        
        <view class="form-item">
          <text class="form-label required">服务分类</text>
          <radio-group @change="onCategoryChange" class="radio-group">
            <label class="radio-item">
              <radio value="preventive" :checked="formData.category === 'preventive'" color="#007aff"/>
              <text class="radio-text">预防保健</text>
            </label>
            <label class="radio-item">
              <radio value="restoration" :checked="formData.category === 'restoration'" color="#007aff"/>
              <text class="radio-text">牙齿修复</text>
            </label>
            <label class="radio-item">
              <radio value="orthodontics" :checked="formData.category === 'orthodontics'" color="#007aff"/>
              <text class="radio-text">正畸治疗</text>
            </label>
            <label class="radio-item">
              <radio value="periodontal" :checked="formData.category === 'periodontal'" color="#007aff"/>
              <text class="radio-text">牙周治疗</text>
            </label>
            <label class="radio-item">
              <radio value="endodontics" :checked="formData.category === 'endodontics'" color="#007aff"/>
              <text class="radio-text">牙体牙髓病治疗</text>
            </label>
            <label class="radio-item">
              <radio value="oral_surgery" :checked="formData.category === 'oral_surgery'" color="#007aff"/>
              <text class="radio-text">口腔外科手术</text>
            </label>
            <label class="radio-item">
              <radio value="pediatric" :checked="formData.category === 'pediatric'" color="#007aff"/>
              <text class="radio-text">儿童牙科</text>
            </label>
            <label class="radio-item">
              <radio value="implant" :checked="formData.category === 'implant'" color="#007aff"/>
              <text class="radio-text">种植牙</text>
            </label>
          </radio-group>
          <text v-if="errors.category" class="error-text">{{ errors.category }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">服务描述</text>
          <textarea 
            v-model="formData.description" 
            class="form-textarea" 
            placeholder="请输入服务详细描述"
            maxlength="500"
          />
          <text class="char-count">{{ formData.description.length }}/500</text>
        </view>

        <view class="form-item">
          <text class="form-label">服务图片</text>
          <uni-file-picker 
            v-model="imageFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handleImageSelect"
            @delete="handleImageDelete"
          />
          <text class="form-hint">建议尺寸：750x400像素，支持jpg、png格式，最大5MB</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">价格与时长</text>
        
        <view class="form-item">
          <text class="form-label required">基础价格（元）</text>
          <uni-easyinput 
            v-model="formData.base_price"
            type="number"
            placeholder="请输入服务价格"
            :clearable="true"
          />
          <text v-if="errors.base_price" class="error-text">{{ errors.base_price }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">预计时长（分钟）</text>
          <uni-easyinput 
            v-model="formData.estimated_duration_minutes"
            type="number"
            placeholder="请输入预计服务时长"
            :clearable="true"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">医生要求</text>
        
        <view class="form-item">
          <text class="form-label">所需医生专科</text>
          <view class="checkbox-group">
            <label v-for="(specialty, index) in specialtyOptions" :key="index" class="checkbox-item">
              <checkbox 
                :value="specialty.value" 
                :checked="formData.required_doctor_specialties.includes(specialty.value)"
                @tap="toggleSpecialty(specialty.value)"
                color="#007aff"
              />
              <text class="checkbox-text">{{ specialty.label }}</text>
            </label>
          </view>
          <text class="form-hint">选择可提供此服务的医生专科</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label">促销信息</text>
          <view class="checkbox-group">
            <label v-for="(promotion, index) in promotionOptions" :key="promotion._id || index" class="checkbox-item" @click="togglePromotion(promotion)">
              <checkbox 
                :value="promotion._id" 
                :checked="selectedPromotions.includes(promotion._id)"
                color="#007aff"
              />
              <text class="checkbox-text">{{ promotion.title }}</text>
            </label>
          </view>
          <text v-if="selectedPromotionsDisplay" class="form-hint">已选: {{ selectedPromotionsDisplay }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.status === 1" color="#007aff"/>
              <text class="radio-text">上架</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.status === 2" color="#007aff"/>
              <text class="radio-text">下架</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.status === 3" color="#007aff"/>
              <text class="radio-text">禁用</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const imageFileList = ref([])
const promotionOptions = ref([])
const selectedPromotions = ref([])

const formData = reactive({
  service_name: '',
  service_code: '',
  service_type: 1,
  category: 'preventive',
  description: '',
  image: '',
  base_price: '',
  estimated_duration_minutes: '',
  required_doctor_specialties: [],
  promotion_description: '',
  status: 1
})

const selectedPromotionsDisplay = computed(() => {
  if (selectedPromotions.value.length === 0) return ''
  
  const selectedItems = promotionOptions.value.filter(p => 
    p._id && selectedPromotions.value.includes(p._id)
  )
  return selectedItems.map(p => p.title).join('、')
})

const errors = reactive({
  service_name: '',
  service_type: '',
  category: '',
  base_price: ''
})

const specialtyOptions = [
  { value: '口腔全科', label: '口腔全科' },
  { value: '牙体牙髓科', label: '牙体牙髓科' },
  { value: '牙周科', label: '牙周科' },
  { value: '口腔修复科', label: '口腔修复科' },
  { value: '口腔正畸科', label: '口腔正畸科' },
  { value: '口腔种植科', label: '口腔种植科' },
  { value: '儿童口腔科', label: '儿童口腔科' },
  { value: '口腔颌面外科', label: '口腔颌面外科' }
]

onMounted(async () => {
  await loadPromotions()
})

async function loadPromotions() {
  try {
    const db = uniCloud.database()
    const res = await db.collection('dh-hospital_promotions')
      .where({ status: 1 }) // 只加载启用状态的促销
      .field('_id, title, discount_type, discount_value, special_price')
      .get()
    
    const promotions = res.result?.data || res.data || []
    promotionOptions.value = promotions
  } catch (err) {
    uni.showToast({ 
      title: '加载促销列表失败：' + (err.message || '未知错误'), 
      icon: 'none' 
    })
  }
}

function togglePromotion(promotion) {
  if (!promotion._id) return
  
  const index = selectedPromotions.value.indexOf(promotion._id)
  if (index > -1) {
    selectedPromotions.value.splice(index, 1)
  } else {
    selectedPromotions.value.push(promotion._id)
  }
  
  // 更新促销描述
  updatePromotionDescription()
}

function updatePromotionDescription() {
  if (selectedPromotions.value.length === 0) {
    formData.promotion_description = ''
    return
  }
  
  const selectedItems = promotionOptions.value.filter(p => 
    p._id && selectedPromotions.value.includes(p._id)
  )
  
  const descriptions = selectedItems.map(promotion => {
    let desc = promotion.title
    if (promotion.discount_type === 1) {
      // 百分比折扣：0.8表示8折
      const discount = promotion.discount_value * 10
      desc += ` - ${discount}折优惠`
    } else if (promotion.discount_type === 2) {
      // 固定金额减免
      desc += ` - 立减${promotion.discount_value}元`
    } else if (promotion.discount_type === 3) {
      // 满减优惠
      desc += ` - 满减${promotion.discount_value}元`
    } else if (promotion.discount_type === 4) {
      // 特价
      desc += ` - 特价 ¥${promotion.special_price || promotion.discount_value}`
    }
    return desc
  })
  
  formData.promotion_description = descriptions.join('；')
}

function onServiceTypeChange(e) {
  formData.service_type = parseInt(e.detail.value)
  errors.service_type = ''
}

function onCategoryChange(e) {
  formData.category = e.detail.value
  errors.category = ''
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function toggleSpecialty(value) {
  const index = formData.required_doctor_specialties.indexOf(value)
  if (index > -1) {
    formData.required_doctor_specialties.splice(index, 1)
  } else {
    formData.required_doctor_specialties.push(value)
  }
}

function handleImageSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    imageFileList.value = e.tempFiles
  }
}

function handleImageDelete(e) {
  imageFileList.value = []
}

async function uploadImageToCloud() {
  if (!imageFileList.value || imageFileList.value.length === 0) {
    return null
  }
  
  try {
    const tempFile = imageFileList.value[0]
    const uploadResult = await uniCloud.uploadFile({
      filePath: tempFile.path,
      cloudPath: `services/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${tempFile.name.split('.').pop()}`
    })
    // 返回符合数据库schema的file对象结构（用于add操作）
    return {
      name: uploadResult.fileID.split('/').pop(),
      extname: tempFile.name.split('.').pop(),
      url: uploadResult.fileID,
      size: tempFile.size || 0,
      file_id: uploadResult.fileID
    }
  } catch (err) {
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.service_name || formData.service_name.trim().length === 0) {
    errors.service_name = '请输入服务名称'
    isValid = false
  } else {
    errors.service_name = ''
  }
  
  if (!formData.category) {
    errors.category = '请选择服务分类'
    isValid = false
  } else {
    errors.category = ''
  }
  
  if (!formData.base_price || parseFloat(formData.base_price) <= 0) {
    errors.base_price = '请输入有效的服务价格'
    isValid = false
  } else {
    errors.base_price = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    let uploadedImageUrl = ''
    if (imageFileList.value && imageFileList.value.length > 0) {
      try {
        uni.showLoading({ title: '上传图片中...' })
        uploadedImageUrl = await uploadImageToCloud()
      } catch (uploadErr) {
        uni.hideLoading()
        uni.showToast({ 
          title: '图片上传失败：' + (uploadErr.message || '未知错误'), 
          icon: 'none'
        })
        return
      }
    }
    
    const db = uniCloud.database()
    
    // 构建提交数据（hospital_id将由云函数自动添加）
    const submitData = {
      service_name: formData.service_name,
      service_code: formData.service_code,
      service_type: formData.service_type,
      category: formData.category,
      description: formData.description,
      base_price: parseFloat(formData.base_price) || 0,
      estimated_duration_minutes: parseInt(formData.estimated_duration_minutes) || 0,
      required_doctor_specialties: formData.required_doctor_specialties,
      promotion_description: formData.promotion_description,
      status: formData.status
    }
    
    // 只有有图片URL时才添加image字段
    if (uploadedImageUrl) {
      submitData.image = uploadedImageUrl
    }
    
    // 调用云对象方法创建服务（会自动挂载 hospital_id）
    const servicesObj = uniCloud.importObject('dh-services')
    const result = await servicesObj.createService(submitData)
    
    uni.hideLoading()
    
    // 判断创建是否成功
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/business/services/list'
        })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '创建失败', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ 
      title: err.message || '创建失败', 
      icon: 'none'
    })
  }
}

function handleCancel() {
  uni.redirectTo({
    url: '/pages/business/services/list'
  })
}
</script>

<style lang="scss" scoped>
.service-add-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.char-count {
  font-size: 24rpx;
  color: #999;
  display: block;
  text-align: right;
  margin-top: 8rpx;
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
  min-width: 200rpx;
}

.checkbox-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
